﻿//Dùng tại:
//      + frmWaiting
//      + frmConfigDatabase

using System;
using System.Text;
using System.IO;
using System.Data;
using System.Data.SqlClient;

namespace prjKQXS_DLL
{
    public class Config
    {
        /// <summary>
        /// Truyền vào chuỗi kết nối và lấy ra các thành phần
        /// </summary>
        /// <param name="connString"></param>
        /// <param name="source">Dùng để lấy ra Data source</param>
        /// <param name="user">Dùng để lấy ra User ID</param>
        /// <param name="pass">Dùng để lấy ra Password</param>
        public static void getConnectionProperties(string connString, ref string source, ref string user, ref string pass)
        {
            //SqlConnection conn = new SqlConnection(connString);
            //source = conn.DataSource;
            
            string[] s = connString.Split(';');

            foreach (string ss in s)
            {
                if (ss.Trim().ToUpper().Contains("DATA SOURCE"))
                {
                    source = ss.Split('=')[1].Trim();
                }
                else if (ss.Trim().ToUpper().Contains("USER ID"))
                {
                    user = ss.Split('=')[1].Trim();
                }
                else if (ss.Trim().ToUpper().Contains("PASSWORD"))
                {
                    pass = ss.Split('=')[1].Trim();
                }
            }
        }

        /// <summary>
        /// Kiểm tra kết nối theo chuỗi kết nối truyền vào
        /// </summary>
        /// <param name="connString"></param>
        /// <returns></returns>
        public static bool testConnection(string connString)
        {
            bool ok = false;
            SqlConnection conn = new SqlConnection(connString);

            try
            {
                conn.Open();
                if (conn.State == ConnectionState.Open) ok = true;
            }
            catch (Exception ex)
            {
                ok = false;
            }
            finally
            {
                conn.Close();
            }

            return ok;
        }
        
        
        /// <summary>
        /// Mã hóa chuỗi connString truyền vào và viết thành tệp config.ini
        /// </summary>
        /// <param name="connString"></param>
        public static void writeConfig(string connString)
        {
            Encrypt e = new Encrypt();
            connString = e.encrypt(connString, BienTc.encryptString, true);
            using (FileStream fs = File.Create(BienTc.fileIni, 1024))
            {
                // Add some information to the file.
                byte[] info = new System.Text.UTF8Encoding(true).GetBytes(connString);
                fs.Write(info, 0, info.Length);
            }
        }

        /// <summary>
        /// Giải mã nội dung tệp config.ini để lấy ra chuỗi kết nối
        /// </summary>
        /// <returns></returns>
        public static string loadConfig()
        {
            string connString = "";

            if (File.Exists(BienTc.fileIni))
            {
                using (StreamReader sr = File.OpenText(BienTc.fileIni))
                {
                    string s = "";
                    while ((s = sr.ReadLine()) != null)
                    {
                        connString = s;
                    }
                }
            }

            Encrypt e = new Encrypt();
            if (!connString.Trim().Equals(""))
                connString = e.Decrypt(connString, BienTc.encryptString, true);

            return connString;
        }

        public static int getUR_Quyen(string UName, string Tacvu)
        {
            SqlConnection conn = new SqlConnection(Config.loadConfig());
            if (conn.State != ConnectionState.Open)
                conn.Open();
            SqlCommand cmd = new SqlCommand("proc_Users_getQuyen", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UName", UName);
            cmd.Parameters.AddWithValue("@IID", Tacvu);
            try
            {
                return Int32.Parse(cmd.ExecuteScalar().ToString());
            }
            catch
            {
                return getUR_Quyen(UName, Tacvu, conn);
            }
            finally
            {
                cmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }

        public static int getUR_Quyen(string UName, string Tacvu, SqlConnection sqlconn)
        {
            if (sqlconn.State != ConnectionState.Open)
                sqlconn.Open();
            SqlCommand cmd = new SqlCommand("proc_Users_getQuyen", sqlconn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UName", UName);
            cmd.Parameters.AddWithValue("@IID", Tacvu);
            try
            {
                int q = Int32.Parse(cmd.ExecuteScalar().ToString());
                return q;
            }
            catch
            {
                return 5;
            }
            finally
            {
                cmd.Dispose();
            }
        }

        public static void Errlog(string Vtri, string TxTNoidung)
        {
            try
            {
                if (!Directory.Exists(BienTc.applog))
                {
                    Directory.CreateDirectory(BienTc.applog);
                }
                string Ngay = DateTime.Now.ToString();
                string luc = DateTime.Now.ToString("dd_MM_yyyy_HH:mm:ss");
                string LogKey = "AppLog" + DateTime.Now.ToString("dd_MM_yyyy");
                string LogFile = LogKey + @".ini";
            }
            catch (Exception)
            {

            }

        }
    }
}
